<template>
  <div>
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
      status-icon
    >
      <el-form-item label="文章标题" prop="title">
        <el-input v-model="ruleForm.title" />
      </el-form-item>
      <el-form-item label="上传图片" prop="img">
        <el-upload
          action="/api/api/upload"
          list-type="picture-card"
          :on-success="uploadFile"
          :multiple="false"
          :on-change="uploadImg"
          :file-list="fileList"
        >
          <el-icon><Plus /></el-icon>

          <template #file="{ file }">
            <div>
              <img
                class="el-upload-list__item-thumbnail"
                :src="file.url"
                alt=""
              />
              <span class="el-upload-list__item-actions">
                <span
                  v-if="!disabled"
                  class="el-upload-list__item-delete"
                  @click="handleRemove"
                >
                  <el-icon><delete /></el-icon>
                </span>
              </span>
            </div>
          </template>
        </el-upload>
      </el-form-item>

      <el-form-item label="文章描述" prop="explain">
        <el-input v-model="ruleForm.explain" />
      </el-form-item>
      <el-form-item label="文章内容" prop="content">
        <div style="border: 1px solid #ccc">
          <Toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="editorRef"
            :defaultConfig="toolbarConfig"
          />
          <Editor
            style="height: 500px; overflow-y: hidden"
            v-model="valueHtml"
            :defaultConfig="editorConfig"
            @onChange="handleChange"
            @onCreated="handleCreated"
          />
        </div>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          Create
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang='ts' setup>
import { ref, reactive, toRefs, computed } from "vue";
import { useStore } from "vuex";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css

import { onBeforeUnmount, shallowRef, onMounted } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { uploadFile, addArticle } from "../utils/api";
import { Delete, Download, Plus, ZoomIn } from "@element-plus/icons-vue";
import type { UploadFile } from "element-plus";
import axios from "axios";
import type { FormInstance, FormRules } from "element-plus";
import { useRouter, useRoute } from "vue-router";
import { data } from "dom7";
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive({
  title: "",
  img: "", //图片地址
  image: "", //存放图片id
  explain: "",
  content: "",
});
const loading = ref(false);
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
// 内容 HTML
const valueHtml = ref("<p></p>");

// 模拟 ajax 异步获取内容
onMounted(() => {
  setTimeout(() => {
    valueHtml.value = "<p>1111</p>";
  }, 1500);
});

const toolbarConfig = {};
const editorConfig = { placeholder: "请输入内容..." };

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});
const handleChange = (editor: any) => {
  ruleForm.content = valueHtml.value;
};
const handleCreated = (editor: any) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};
const store = useStore();
const router = useRouter();
const userlist = computed(() => store.state.user);
// 存放图片列表
const fileList = ref([]);
// 默认隐藏
const disabled = ref(false);
//图片显示
const upLoad = ref("inline-block");
//图片删除
const handleRemove = () => {
  fileList.value = [];
  upLoad.value = "inline-block";
  ruleForm.img = "";
};
// 添加图片id
const uploadImg = (file: any) => {
  if (file) {
    let formDataUp = new FormData();
    formDataUp.append("file", file.raw);
    upLoad.value = "none";
    uploadFile(formDataUp).then((res) => {
      ruleForm.image = res.data._id;
      ruleForm.img = "" + res.data.url;
    
    });
  }
};

const rules = reactive<FormRules>({
  title: [{ required: true, message: "请输入文章标题", trigger: "blur" }],
  explain: [{ required: true, message: "请输入文章描述", trigger: "blur" }],
  content: [{ required: true, message: "请输入文章内容", trigger: "blur" }],
});
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    loading.value = true;
    if (valid) {
      let form: any = {};
      if (ruleForm.image == "") {
        form = {
          title: "1234",
          content: "123",
          // 用户信息
          author: userlist.value._id,
          column: userlist.value.column,
        };
      } else {
        form = {
          title: ruleForm.title,
          content: ruleForm.content,
          image: ruleForm.image,
          // 用户信息
          author: userlist.value._id,
          column: userlist.value.column,
        };
      }
      addArticle(form).then(async (res) => {
        await router.push(`/?author=${userlist.value.column}`);
        alert('添加成功')
      });
    } else {
      console.log("添加失败");
    }
  });
};
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>

<style scoped lang='scss'>
</style>